package com.example.shop_2302.utils

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

class SingData<T>:MutableLiveData<T> (){
    var flag = AtomicBoolean(false)//设置全局变量，用来监听数据是否发生了变化

    //值发生变化
    override fun postValue(value: T) {
        flag.set(true)
        super.postValue(value)
    }
    //观察值变化
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner){
            //数据更新后，需要将flag重新修改false
            if(flag.compareAndSet(true,false)){
                observer.onChanged(it)
            }
        }
    }
}